/*

Version 0.1
SEMF - Web Desiging Framework for Sport Event Managment
Copyright (C) 2006, SEMF Developers

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
/**
 * All the function to call asynchronously to backend logic and work with responses
 * Also contain auxilary functions to support above mentioned
 * @version 1.0
 */
 
 var selectedModule = null;
 var selectedProject = null;
 var selectedModuleDirectory = null;
 
 var panelStatus = 0;
 
 var MODULE_HOME = 1;
 var PAGE_EDITOR = 2;
 var ENTITY_EDITOR = 3;
 var ATTR_EDITOR = 4;
 
 var PAGE_DESIGNER = 5;
 var EDIT_INHERITANCE = 6;
 
 //Requried variable for the dir utils..
 
 SEMF.currentPanel = null;
 SEMF.sampleDirPanel = null;
 
 var currentPanelId = 0;
 
 SEMF.dirWinOked = false;
 
 //=======================================================================================//
// Function to call to asynchronously to backend logic and get data for the module 
// Then replace the correct DOM with the retuned data
// @args module_name Module name for which the DOM is prepared for

function getModuleData(moduleName,projectHome){
	var div;
	
	//function to handle success
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			//replace the identified tag with the response text
			//this response contain either tables for the modules if they exist or message saying it doen't exit
			div.innerHTML =  o.responseText ;	
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	
	//set the div tag
	div = document.getElementById('panel2_content');
	var title= document.getElementById('panel2_hd');
	
	//set the module name in header of right side panel
	title.innerHTML='<div class="tl"></div><span><b> '+moduleName+'</b></span><div class="tr"></div>';
	//set the value of the url
	url='../lib/tables/list_tables.php?module='+moduleName+'&project_home='+projectHome;
	
	panelStatus = ENTITY_EDITOR;
	
	var iframe = document.getElementById("mainIframe");
	var user_token_input_ctrl = document.getElementById("user_token_input");
	var project_dir_input_ctrl = document.getElementById("project_dir_input");
	var user_token = user_token_input_ctrl.value;
	var project_dir = project_dir_input_ctrl.value;
	
	func_name = 'getModuleData';
	status = "&status="+ panelStatus;
	iframe.src= "frame_loader.php?func="+func_name+ status +'&param1='+moduleName + "&param2="+projectHome + "&user_token=" + user_token + "&project_dir=" + project_dir;
	
	//call the request
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);

  
}
//==============================================================================//
// Load Show page designer and table designer switches
// @arg moduleName, name of the module
// @arg projectHome, project directory 
function getProjectData(moduleName, projectHome){
	var div;
	
	selectedModule = moduleName;
	
	//function to handle success
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			//replace the identified tag with the response text
			//this response contain either tables for the modules if they exist or message saying it doen't exit
			div.innerHTML =  o.responseText ;	
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	
	//set the div tag
	div = document.getElementById('panel2_content');
	var title= document.getElementById('panel2_hd');
	
	//set the module name in header of right side panel
	title.innerHTML='<div class="tl"></div><span><b> '+moduleName+'</b></span><div class="tr"></div>';
	//set the value of the url
	url='module_data.php?module='+moduleName + "&project_home="+projectHome;
	
	panelStatus = MODULE_HOME;
	
	var iframe = document.getElementById("mainIframe");
	var user_token_input_ctrl = document.getElementById("user_token_input");
	var project_dir_input_ctrl = document.getElementById("project_dir_input");
	var user_token = user_token_input_ctrl.value;
	var project_dir = project_dir_input_ctrl.value;
	
	func_name = 'getProjectData';
	status = "&status="+ panelStatus;
	iframe.src= "frame_loader.php?func="+func_name+status+'&param1='+moduleName + "&param2="+projectHome + "&user_token=" + user_token + "&project_dir=" + project_dir;
	
	//call the request
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
  
}


/** just changed for convenience to seperate schema and pages... */
function getModulePageData(moduleName, projectHome){
	var div;
	
	//function to handle success
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			//replace the identified tag with the response text
			//this response contain either tables for the modules if they exist or message saying it doen't exit
			div.innerHTML =  o.responseText ;	
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	
	//set the div tag
	div = document.getElementById('panel2_content');
	var title= document.getElementById('panel2_hd');
	
	//set the module name in header of right side panel
	title.innerHTML='<div class="tl"></div><span><b> '+moduleName+'</b></span><div class="tr"></div>';
	//set the value of the url
	url='../lib/pages/list_pages.php?module='+moduleName + "&project_home="+projectHome;
	
	panelStatus = PAGE_EDITOR;
	
	var iframe = document.getElementById("mainIframe");
	var user_token_input_ctrl = document.getElementById("user_token_input");
	var project_dir_input_ctrl = document.getElementById("project_dir_input");
	var user_token = user_token_input_ctrl.value;
	var project_dir = project_dir_input_ctrl.value;
	
	func_name = 'getModulePageData';
	status = "&status="+ panelStatus;
	iframe.src= "frame_loader.php?func="+func_name+status+'&param1='+moduleName + "&param2="+projectHome + "&user_token=" + user_token + "&project_dir=" + project_dir;
	
	//call the request
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}


//=======================================================================================//
// Function to call to asynchronously to backend logic and get data for the module 
// Then replace the correct DOM with the retuned data
// @args module_name Module name for which the DOM is prepared for

function getModuleSchemaData(moduleName, projectHome){
	var div;
	
	//function to handle success
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			//replace the identified tag with the response text
			//this response contain either tables for the modules if they exist or message saying it doen't exit
			div.innerHTML =  o.responseText ;	
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	
	//set the div tag
	div = document.getElementById('panel2_content');
	var title= document.getElementById('panel2_hd');
	
	//set the module name in header of right side panel
	title.innerHTML='<div class="tl"></div><span><b> '+moduleName+'</b></span><div class="tr"></div>';
	//set the value of the url
	url='../lib/tables/list_tables.php?module='+moduleName + "&project_home="+projectHome;
	
	panelStatus = ENTITY_EDITOR;
	
	var iframe = document.getElementById("mainIframe");
	var user_token_input_ctrl = document.getElementById("user_token_input");
	var project_dir_input_ctrl = document.getElementById("project_dir_input");
	var user_token = user_token_input_ctrl.value;
	var project_dir = project_dir_input_ctrl.value;
	
	func_name = 'getModuleSchemaData';
	status = "&status="+ panelStatus;
	iframe.src= "frame_loader.php?func="+func_name+status+'&param1='+moduleName + "&param2="+projectHome + "&user_token=" + user_token + "&project_dir=" + project_dir;
	
	//call the request
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
  
}


//=====================================================//
// Function to trim a string
// @args string to be trimmed
// @return trimmed string
function trim(str){
	
	//remove the spaces from at the start
	while( str.substr(0,1) == ' '){
		str=str.substr(1);
	};
	
	//remove spaces at the end
	while( str.substr(str.length-1,1) == ' '){
		str=str.substr(0,str.length-1);
	};
	
	//returned the trimmed string
	return str;
}

function addTableMode(moduleName,projectHome){
	//if another field is being edited cancel that edit before starting new edit
	var formBody;
	var handlerOk = function() {
		var dataObject=getData(document.getElementById("inputform"));
	
		var tableName=trim(dataObject.tablename);
		if (tableName == '') {
			alert('Entity name cannot be blank!');
			return ;
		}
		
		addTable(tableName,moduleName,projectHome);
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';

	}; //default yes action
	var handlerCancel = function (){
	//alert("NO is seleted");
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';
	}
	
	formBody=document.getElementById('dialogbody');
	YAHOO.schema.container.inputDialog.show();
	//alert(formBody);
	formBody.innerHTML= '<form name="inputform" method="POST"  id="inputform">'+
      '<label for="tablename">Entity Name </label>'+	  
	  '<input type="text" name="tablename" id="tablename" />'+
	  '</form>';

	//set up button, link to handler
	var myButtons = [ { text:"Ok", handler:handlerOk, isDefault:true },{text:"Cancel",handler:handlerCancel} ];

	//put buttons in configuration queue for processing
	YAHOO.schema.container.inputDialog.cfg.queueProperty("buttons", myButtons);
	YAHOO.schema.container.inputDialog.setHeader('<div class="tl"></div><span>Add Entity</span><div class="tr"></div>');
	YAHOO.schema.container.inputDialog.render();
	YAHOO.schema.container.inputDialog.show();
}
function editTableMode(tableName,tableId,moduleName,projectHome){
	//if another field is being edited cancel that edit before starting new edit
	var formBody;
	var handlerOk = function() {
		var dataObject=getData(document.getElementById("inputform"));
	
		var newName=trim(dataObject.tablename);
		if(newName == ''){
			alert('Entity name cannot be blank');
			return ;
		}
		if(newName != tableName) {
			renameTable(newName,tableId,moduleName,projectHome);
		}
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';

	}; //default yes action
	var handlerCancel = function (){
	//alert("NO is seleted");
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';
	}
	
	formBody=document.getElementById('dialogbody');
	YAHOO.schema.container.inputDialog.show();
	formBody.innerHTML= '<form name="inputform" method="POST"  id="inputform">'+
      '<label for="tablename">Entity Name </label>'+	  
	  '<input type="text" name="tablename" id="tablename" value="'+tableName+'"/>'+
	  '</form>';

	//set up button, link to handler
	var myButtons = [ { text:"Yes", handler:handlerOk, isDefault:true },{text:"No",handler:handlerCancel} ];

	//put buttons in configuration queue for processing
	YAHOO.schema.container.inputDialog.cfg.queueProperty("buttons", myButtons);
	YAHOO.schema.container.inputDialog.setHeader('<div class="tl"></div><span>Rename Entity</span><div class="tr"></div>');
	YAHOO.schema.container.inputDialog.render();

	YAHOO.schema.container.inputDialog.show();
}
//===========================================================================//
// Funtion to add a table to the module by calling (async) to backend logic
// and reloading the DOM after table is created
// @args tableName, new table name
// @args moduleName, module name
// @args projectHome, project home directory
function addTable(tableName,moduleName,projectHome){
	if(tableName==''){
		alert('please enter a valid name for the table');
		return;
	}else{
		url='../lib/tables/table_actions.php?action=new&table_name='+tableName+'&module='+moduleName+'&project_home='+projectHome;
		var suc= function(o){
			getModuleData(moduleName,projectHome);
		}
		var fail= function(o){
			alert('it failed');
		}
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
	}
}


//delete table and update the user interface
//===========================================================================//
// Funtion to delete a table from the module by calling (async) to backend logic
// and reloading the DOM after table is deleted
// @args tableId,  table id of the module.xml document ordering
// @args module, module name
function deleteTable(tableId,module,projectHome){
	//if user confirm the deletion continue to delete
	if(confirm('Do you want to delete this table ?')){
	
		url='../lib/tables/table_actions.php?action=delete&table_id='+tableId+'&module='+module+'&project_home='+projectHome;
		var suc= function(o){
			getModuleData(module,projectHome);
		}
		var fail= function(o){
			//request failed 
	    }
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
	
	}
}


//===========================================================================//
// Funtion to add a table to the module by calling (async) to backend logic
// and reloading the DOM after table is created
// @args tableName, Old name of the table
// @args tableId, id of the table name
// @args moduleName, module name
function renameTable(tableName,tableId,moduleName,projectHome){

			url='../lib/tables/table_actions.php?action=edit&table_id='+tableId+'&module='+moduleName+'&table_name='+tableName+'&project_home='+projectHome;
			var suc= function(o){
				getModuleData(moduleName,projectHome);
			}
			var fail= function(o){
			// request failed
			}
			var callbackfn={ success:suc,failure:fail };
			var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);

}


function addModuleMode(project,projectDir){
	var formBody;
	var handlerOk = function() {
		var dataObject=getData(document.getElementById("inputform"));
	
		var newName=dataObject.modulename;
		if(trim(newName) == ''){
			alert('Module name cannot be blank');
		}
		addModule(newName,projectDir);
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';

	}; //default yes action
	var handlerCancel = function (){
	//alert("NO is seleted");
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';
	}
	
	formBody=document.getElementById('dialogbody');
	YAHOO.schema.container.inputDialog.show();
	formBody.innerHTML= '<form name="inputform" method="POST"  id="inputform">'+
      '<label for="modulename">Module Name </label>'+	  
	  '<input type="text" name="modulename" id="modulename"/>'+
	  '</form>';

	//set up button, link to handler
	var myButtons = [ { text:"Ok", handler:handlerOk, isDefault:true },{text:"Cancel",handler:handlerCancel} ];

	//put buttons in configuration queue for processing
	YAHOO.schema.container.inputDialog.cfg.queueProperty("buttons", myButtons);
	YAHOO.schema.container.inputDialog.setHeader('<div class="tl"></div><span>Add Module</span><div class="tr"></div>');
	YAHOO.schema.container.inputDialog.render();

	YAHOO.schema.container.inputDialog.show();
}

//add Module and upadte interface
//===============================================================================//
// Function to add module
// @args module, module id
function addModule(moduleName, projectDir){
		url='../lib/modules/module_actions.php?action=new&module_name='+moduleName+'&'+
					'project_dir='+projectDir;
		var suc= function(o)
		{
			getProjectData(moduleName, projectDir);
			getModuleList(projectDir);
		}
		var fail= function(o){
			// request failed
		}
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
}

//remove Module and upadte interface
//===============================================================================//
// Function to add module
// @args module, module id
function removeModule(project, projectDir)
{
	moduleName = selectedModule;
	if(moduleName==null)
	{
		alert("please select a module to delete");
	}
	else
	{
		if(confirm('Are you sure you want to delete module '+moduleName+' ?'))
		{
			url='../lib/modules/module_actions.php?action=delete&module_name='+moduleName+'&'+
						'project_dir='+projectDir;
			var suc= function(o)
			{
				//set the div tag
				var div = document.getElementById('panel2_content');
				var title= document.getElementById('panel2_hd');
	
				//set the module name in header of right side panel
				title.innerHTML='<div class="tl"></div><span><b></b></span><div class="tr"></div>';
				div.innerHTML='&nbsp;';
				getModuleList(projectDir);
			}
			var fail= function(o){
				// request failed
			}
			var callbackfn={ success:suc,failure:fail };
			
			var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
		}
	}
}

//=============================================================//
// Function to list field details of a table
// @arg tableName, name of the table
// @arg tableId, table id of the module.xml document ordering
// @arg moduleName, Module name of the table
function manageFields(tableName,tableId,moduleName,projectHome){
	var div;
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			div.innerHTML =  o.responseText ;	
		}
	}
	var handleFailure = function(o){
		if(o.responseText !== undefined){

		}
	}

	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	div = document.getElementById('panel2_content');
	var title= document.getElementById('panel2_hd');
	title.innerHTML='<div class="tl"></div><span><b>' +moduleName+' >> <i>'+tableName+'</i></b></span><div class="tr"></div>';
	
	url='../lib/fields/list_fields.php?module_name='+moduleName+'&table_id='+tableId+'&project_home='+projectHome;
	
	
	panelStatus = ATTR_EDITOR;
	
	var iframe = document.getElementById("mainIframe");
	var user_token_input_ctrl = document.getElementById("user_token_input");
	var project_dir_input_ctrl = document.getElementById("project_dir_input");
	var user_token = user_token_input_ctrl.value;
	var project_dir = project_dir_input_ctrl.value;
	
	func_name = 'manageFields';
	status = "&status="+ panelStatus;
	iframe.src= "frame_loader.php?func="+func_name+ status + '&param1='+tableName+ '&param2='+tableId+'&param3='+moduleName +"&param4="+projectHome + "&user_token=" + user_token + "&project_dir=" + project_dir;
	
  	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);


}


//=============================================================================//
// Function to edit fields
// @arg multiplicity
// @arg fieldName, name of the field
// @arg fieldType, type of the field
// @arg fieldId, id of the field
// @arg tableId, Index of table in xml file
// @arg moduleName, Module name
function editFieldMode(multiplicity,fieldName,fieldType,fieldId,tableId,moduleName,projectHome){
	//if another field is being edited cancel that edit before starting new edit
	var formBody;
	var handlerOk = function() {
		var dataObject=getData(document.getElementById("inputform"));
	
		var fieldName=trim(dataObject.fieldname);
		var fieldType,isArray;
		
		if(dataObject.isarray){
			isArray="yes";
		}else{
			isArray="no";
		}
		if((fieldName) == ''){
			alert('Attribute name cannot be blank!');
			return;
		}
		if ((fieldType=setFieldType(dataObject)) == ''){
			return;
		}
		editField(fieldId,fieldName,fieldType,isArray,tableId,moduleName,projectHome);
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';

	}; //default yes action
	var handlerCancel = function (){
	//alert("NO is seleted");
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';
	}
	
	formBody=document.getElementById('dialogbody');
	var typeModule,typeTable;
	typeModule=extractTypeModule(fieldType);
	typeTable=extractTypeTable(fieldType);
	fieldType=extractFieldType(fieldType);
	
	YAHOO.schema.container.inputDialog.show();
		
	formBody.innerHTML= setFieldDialogHTML(fieldName,fieldType,multiplicity,projectHome);

	//set up button, link to handler
	var myButtons = [ { text:"Yes", handler:handlerOk, isDefault:true },{text:"No",handler:handlerCancel} ];

	//put buttons in configuration queue for processing
	YAHOO.schema.container.inputDialog.cfg.queueProperty("buttons", myButtons);
	YAHOO.schema.container.inputDialog.setHeader('<div class="tl"></div><span>Edit Field</span><div class="tr"></div>');
	YAHOO.schema.container.inputDialog.render();

	if(typeModule && typeTable){
			getTypeModuleOptions("typemodule",typeModule,projectHome);
			getTypeTableOptions("typetable",typeModule,typeTable,projectHome);
	}
	YAHOO.schema.container.inputDialog.show();
}

function addFieldMode(tableId,moduleName,projectHome){
	//if another field is being edited cancel that edit before starting new edit
	var formBody;
	var handlerOk = function() {
		var dataObject=getData(document.getElementById("inputform"));
	
		var fieldName=dataObject.fieldname;
		var fieldType,isArray;
		
		if(dataObject.isarray){
			isArray="yes";
		}else{
			isArray="no";
		}
		
		if((fieldName) == ''){
			alert('Attribute name cannot be blank!');
			return;
		}
		if ((fieldType=setFieldType(dataObject)) == ''){
			return;
		}
		addField(fieldName,fieldType,isArray,tableId,moduleName,projectHome);
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';

	}; //default yes action
	var handlerCancel = function (){
	//alert("NO is seleted");
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';
	}
	
	formBody=document.getElementById('dialogbody');
	var typeModule,typeTable,fieldType;
	if(fieldType){
		typeModule=extractTypeModule(fieldType);
		typeTable=extractTypeTable(fieldType);
		fieldType=extractFieldType(fieldType);
	}
	
	YAHOO.schema.container.inputDialog.show();
		
	formBody.innerHTML= setFieldDialogHTML('',fieldType,'(S)',projectHome);

	//set up button, link to handler
	var myButtons = [ { text:"Yes", handler:handlerOk, isDefault:true },{text:"No",handler:handlerCancel} ];

	//put buttons in configuration queue for processing
	YAHOO.schema.container.inputDialog.cfg.queueProperty("buttons", myButtons);
	YAHOO.schema.container.inputDialog.setHeader('<div class="tl"></div><span>Add Field</span><div class="tr"></div>');
	YAHOO.schema.container.inputDialog.render();

	if(typeModule && typeTable){
			getTypeModuleOptions("typemodule",typeModule,projectHome);
			getTypeTableOptions("typetable",typeModule,typeTable,projectHome);
	}
	YAHOO.schema.container.inputDialog.show();
}


function setFieldDialogHTML(fieldName,fieldType,multiplicity,projectHome){
		
	return '<form name="inputform" method="POST"  id="inputform">'+
      '<label for="fieldname">Attribute Name </label>'+	  
	  '<input type="text" name="fieldname" id="fieldname" value="'+fieldName+'" />'+
	  '<br /><label for="isarray" >Is Array </label>'+
	  '<input type="checkbox" id="isarray" name="isarray" '+((multiplicity == '(M)')?'checked="checked"':'')+' />'+
	  '<br/><label for="typename">Type Name </label>'+
	  '<select name="typename" id="typename" onchange="javascript:typeChanged(\'inputform\',\'\',\''+projectHome+'\')">'+
	  '<option '+((fieldType=='Text')?' selected="selected"':'')+' value="Text">Text</option>'+
	  '<option '+((fieldType=='Number')?' selected="selected"':'')+' value="Number" >Number</option>'+
	  '<option '+((fieldType=='Date')?' selected="selected"':'')+' value="Date" >Date</option>'+
	  '<option '+((fieldType=='Time')?' selected="selected"':'')+' value="Time">Time</option>'+
	  '<option '+((fieldType=='Image')?' selected="selected"':'')+' value="Image" >Image</option>'+
	  '<option '+((fieldType=='Table')?' selected="selected"':'')+' value="Table">Entity</option>'+
      '</select>'+
	  ((fieldType=='Table')?'<br/><label for="typemodule">Type Module</label>'+
		'<select name="typemodule" id="typemodule" onchange="javascript:moduleChanged(\'inputform\',\''+projectHome+'\')">'+
		'</select><br/><label for="typetable">Type Entity</label>'+
		'<select name="typetable" id="typetable">'+
		'</select>':'')+
	  '</form>';
}
function extractTypeModule(fieldType){
	if(fieldType.substr(0,5) == 'Table'){
		var tableModuleString=fieldType.substr(6);
		var index = tableModuleString.indexOf(".");
		if(index && index > 0){
			return tableModuleString.substr(0,index);
		}
	}
}

function extractTypeTable(fieldType){
	if(fieldType.substr(0,5) == 'Table'){
		var tableModuleString=fieldType.substr(6);
		var index = tableModuleString.indexOf(".");
		if(index && index > 0){
			return tableModuleString.substr(index+1);
		}
	}
}
function extractFieldType(fieldType){
	if(fieldType.substr(0,5) == 'Table'){
		return	'Table';
	}else {
		return fieldType;
	}
}
function setFieldType(dataObject){
		if(dataObject.typename=='Table'){
			var typeModule=dataObject.typemodule;
			var typeTable =dataObject.typetable;
			if(!typeModule || typeModule == '' ){
				alert("You have to select a module if you choose Table type");
				return '';
			}else if(!typeTable || typeTable == '' ){
				alert("You have to select a table from module ");
				return '';
			}
			return 'Table:'+typeModule+'.'+typeTable;
		}else if(dataObject.typename != ''){
			return dataObject.typename;
		}else {
			alert("Invalid type!");
			return '';
		}
}
function typeChanged(formid,typeModule,projectHome){
	
	var fieldName= document.forms[formid].fieldname.value;
	var selectId= document.forms[formid].typename;
	//alert(selectId);
	if(selectId){
		var fieldType = selectId.options[selectId.selectedIndex].value;
	}

	
	if(fieldType == 'Table'){
		//alert('table');
		showTypeModule(fieldName,fieldType,typeModule,projectHome);
		setTimeout("moduleChanged('"+formid+"','"+projectHome+"')",100);
	}else{
		//alert('other');
		hideTypeModule(fieldName,fieldType,typeModule,projectHome);
	}
}

function moduleChanged(formid,projectHome){
	//alert('here');
	var moduleId= document.forms[formid].typemodule;
	var tableId = document.forms[formid].typetable;

	var typeModule='';
	var typeTable='';
	if(!moduleId){
		document.forms[formid].innerHTML+='<br><label for="typemodule">Type Module</label>'+
		'<select name="typemodule" id="typemodule" onchange="javascript:moduleChanged(\'inputform\',\''+projectHome+'\')">'+
		'</select>';
	}else if(moduleId.selectedIndex>=0){
		typeModule = moduleId.options[moduleId.selectedIndex].value;
	}else {
		typeModule = moduleId.options[0].value;
	}
	if(!tableId){
		document.forms[formid].innerHTML+='<br><label for="typetable">Type Entity</label>'+
		'<select name="typetable" id="typetable">'+
		'</select>';
	}else if (tableId.selectedIndex>=0){
	 typeTable= tableId.options[tableId.selectedIndex].value;
	}
	showTypeTable(typeModule,typeTable,projectHome);
	
}
function hideTypeModule(fieldName,fieldType,typeModule,projectHome){
	//alert('hide module '+projectHome);
	var checked=document.getElementById('isarray').checked;
		var formBody=document.getElementById('inputform');
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform">'+
      '<label for="fieldname">Attribute Name </label>'+	  
	  '<input type="text" name="fieldname" value="'+fieldName+'" />'+
	  '<br /> <label for="isarray" >Is Array </label><input type="checkbox" id="isarray" name="isarray" '+((checked)?'checked="checked"':'')+' />'+
	  '<br><label for="typename">Type Name </label>'+
	  '<select name="typename" onchange="javascript:typeChanged(\'inputform\',\''+typeModule+'\',\''+projectHome+'\')" >'+
	  '<option '+((fieldType=='Text')?' selected="selected"':'')+' value="Text">Text</option>'+
	  '<option '+((fieldType=='Number')?' selected="selected"':'')+' value="Number" >Number</option>'+
	  '<option '+((fieldType=='Date')?' selected="selected"':'')+' value="Date" >Date</option>'+
	  '<option '+((fieldType=='Time')?' selected="selected"':'')+' value="Time">Time</option>'+
	  '<option '+((fieldType=='Image')?' selected="selected"':'')+' value="Image" >Image</option>'+
	  '<option '+((fieldType=='Table')?' selected="selected"':'')+' value="Table">Entity</option>'+
      '</select>'+
	  '</form>';

}
function showTypeModule(fieldName,fieldType,typeModule,projectHome){
		hideTypeModule(fieldName,fieldType,typeModule,projectHome);
		var formBody = document.getElementById('inputform');
		var moduleid = document.getElementById('typemodule');
		if(!moduleid){
			formBody.innerHTML+='<br><label for="typemodule">Type Module</label>'+
		'<select name="typemodule" id="typemodule" onchange="javascript:moduleChanged(\'inputform\',\''+projectHome+'\');">'+
		'</select>';
		         getTypeModuleOptions("typemodule",typeModule,projectHome);		
		}else if(moduleid.innerHTML==''){
         getTypeModuleOptions("typemodule",typeModule,projectHome);		
		}
		typeModule = document.getElementById('typemodule').value;
}
function showTypeTable(typeModule,typeTable,projectHome){
	//alert('showtable '+projectHome);
	var formBody = document.getElementById('inputform');
	//showTypeModule(typeModule,projectHome);
	var tableid = document.getElementById('typetable');
	if(!tableid){
		formBody.innerHTML+='<br><label for="typetable">Type Table</label>'+
		'<select name="typetable" id="typetable">'+
		'</select>';
	}
	getTypeTableOptions("typetable",typeModule,typeTable,projectHome);

}

//=============================================================//
// Function to add field to specified table
// @arg fieldName,field name
// @arg fieldType, field type
// @arg tableIndex, index of the current table from module.xml tables
// @arg moduleName, name of the module
function addField(fieldName,fieldType,isArray,tableIndex,moduleName,projectHome){
		url='../lib/fields/field_actions.php?action=new&field_name='+fieldName+'&field_type='+fieldType+'&is_array='+isArray+'&table_id='+tableIndex+'&module='+moduleName+'&project_home='+projectHome;
		var suc= function(o){
			if(o.responseText !== undefined){
			tableName =  o.responseText ;	
			manageFields(tableName,tableIndex,moduleName,projectHome);
			}
			
		}
		var fail= function(o){
			
		}
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
}

	
//=============================================================//
// Function to edit a field of specified table
// @arg fieldId, index of the field in module.xml file
// @arg fieldName, name of the field
// @arg fieldType, type of the field type
// @arg tableIndex, index of the current table from module.xml tables
// @arg moduleName, name of the module
function editField(fieldId,fieldName,fieldType,isArray,tableIndex,moduleName,projectHome){
		url='../lib/fields/field_actions.php?action=edit&field_id='+fieldId+'&field_name='+fieldName+'&field_type='+fieldType+'&is_array='+isArray+'&table_id='+tableIndex+'&module='+moduleName+'&project_home='+projectHome;
		var suc= function(o){
			if(o.responseText !== undefined){
			tableName =  o.responseText ;	
			manageFields(tableName,tableIndex,moduleName,projectHome);
			}
			
		}
		var fail= function(o){
			// request failed
		}
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
}
//=============================================================//
// Function to delete a field ofspecified table
// @arg fieldId, index of the field in module.xml file
// @arg tableIndex, index of the current table from module.xml tables
// @arg moduleName, name of the module
function deleteField(fieldId,tableIndex,moduleName,projectHome){
	if(confirm('Do you want to delete the field ?')){
		url='../lib/fields/field_actions.php?action=delete&field_id='+fieldId+'&table_id='+tableIndex+'&module='+moduleName+'&project_home='+projectHome;
		var suc= function(o){
			if(o.responseText !== undefined){
			tableName =  o.responseText ;	
			manageFields(tableName,tableIndex,moduleName,projectHome);
			}
			
		}
		var fail= function(o){
			// request failed
		}
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
	}
}

function editPageMode(pageName,moduleName,projectHome){
	//if another field is being edited cancel that edit before starting new edit
	var formBody;
	var handlerOk = function() {
		var dataObject=getData(document.getElementById("inputform"));
	
		var newName=trim(dataObject.pagename);
		if(newName == ''){
			alert('Page name cannot be blank');
		}
		if(newName != pageName) {
			renamePage(newName,pageName,moduleName,projectHome);
		}
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';

	}; //default yes action
	var handlerCancel = function (){
	//alert("NO is seleted");
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';
	}
	
	formBody=document.getElementById('dialogbody');
	YAHOO.schema.container.inputDialog.show();
	formBody.innerHTML= '<form name="inputform" method="POST"  id="inputform">'+
      '<label for="pagename">Page Name </label>'+	  
	  '<input type="text" name="pagename" id="pagename" value="'+pageName+'"/>'+
	  '</form>';

	//set up button, link to handler
	var myButtons = [ { text:"Yes", handler:handlerOk, isDefault:true },{text:"No",handler:handlerCancel} ];

	//put buttons in configuration queue for processing
	YAHOO.schema.container.inputDialog.cfg.queueProperty("buttons", myButtons);
	YAHOO.schema.container.inputDialog.setHeader('<div class="tl"></div><span>Edit Page</span><div class="tr"></div>');
	YAHOO.schema.container.inputDialog.render();

	YAHOO.schema.container.inputDialog.show();
}

function addPageMode(moduleName,projectHome){
	//if another field is being edited cancel that edit before starting new edit
	var formBody;
	var handlerOk = function() {
		var dataObject=getData(document.getElementById("inputform"));
	
		var newName=dataObject.pagename;
		if(trim(newName) == ''){
			alert('Page name cannot be blank');
		}
		addPage(newName,moduleName,projectHome);
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';

	}; //default yes action
	var handlerCancel = function (){
	//alert("NO is seleted");
		YAHOO.schema.container.inputDialog.hide();
		formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';
	}
	
	formBody=document.getElementById('dialogbody');
	YAHOO.schema.container.inputDialog.show();
	formBody.innerHTML= '<form name="inputform" method="POST"  id="inputform">'+
      '<label for="pagename">Page Name </label>'+	  
	  '<input type="text" name="pagename" id="pagename" />'+
	  '</form>';

	//set up button, link to handler
	var myButtons = [ { text:"Yes", handler:handlerOk, isDefault:true },{text:"No",handler:handlerCancel} ];

	//put buttons in configuration queue for processing
	YAHOO.schema.container.inputDialog.cfg.queueProperty("buttons", myButtons);
	YAHOO.schema.container.inputDialog.setHeader('<div class="tl"></div><span>Add Page</span><div class="tr"></div>');
	YAHOO.schema.container.inputDialog.render();

	YAHOO.schema.container.inputDialog.show();
}

//The following codes are added to manage Page entries..
function addPage(pageName, moduleName, projectHome)
{
	url='../lib/pages/page_actions.php?action=new&module='+moduleName+
					'&page_name='+pageName+
					'&project_home='+projectHome;
	var suc= function(o){
		getModulePageData(moduleName, projectHome);
	}
	var fail= function(o){
		alert('Failed to create the page..');
	}
	var callbackfn={ success:suc,failure:fail };
	
	var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
}

function renamePage(newName, oldName, moduleName, projectHome)
{
	
	url='../lib/pages/page_actions.php?action=rename&module='+moduleName+
				'&page_name='+oldName+
				'&new_name='+newName+
				'&project_home='+projectHome;
	var suc= function(o){
		getModulePageData(moduleName, projectHome);
	}
	var fail= function(o){
	// request failed
	}
	var callbackfn={ success:suc,failure:fail };
	var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
			
	
}

function deletePage(pageName, pageId, moduleName, projectHome)
{
	if(confirm('Are you sure you want to delete the Page?')){
	
		url='../lib/pages/page_actions.php?action=delete&module='+moduleName+
						'&page_name='+pageName+
						'&project_home='+projectHome;

		var suc= function(o){
			getModulePageData(moduleName, projectHome);
		}
		var fail= function(o){
			//request failed 
	    }
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
	}
}

function editPage(pageName, pageId, moduleName, projectHome)
{
	//panelStatus = PAGE_DESIGNER;
	var resultDir = '../'+projectHome + moduleName + "/";
	
	var iframe = document.getElementById("mainIframe");
	var user_token_input_ctrl = document.getElementById("user_token_input");
	var project_dir_input_ctrl = document.getElementById("project_dir_input");
	var user_token = user_token_input_ctrl.value;
	var project_dir = project_dir_input_ctrl.value;
	
	func_name = 'gotoPageDesigner';
	status = "&status="+ PAGE_DESIGNER;
	iframe.src= "frame_loader.php?func="+func_name+status+'&param1='+resultDir + "&param2="+pageName+ "&param3="+projectHome + "&param4="+moduleName +"&param5="+user_token + "&user_token=" + user_token + "&project_dir=" + project_dir;
}

function gotoPageDesigner(resultDir, pageName, projectHome, moduleName, userToken)
{
	//because paths have been measured w.r.t the pageDesigner..
	url = '../page_designer/index.php?result_dir='+resultDir+ 
					'&page_xml='+resultDir+pageName+ '.xml'+
					'&project_home='+ projectHome +
					'&module_name=' + moduleName +
					'&user_token=' + userToken;
	
	window.location.href = url;
}
function getModuleList(projectDir){
	var div;
	
	//function to handle success
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			//replace the identified tag with the response text
			//this response contain either tables for the modules if they exist or message saying it doen't exit
			div.innerHTML =  o.responseText ;	
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	
	//set the div tag
	div = document.getElementById('moduleListPanel');
	
	//set the value of the url
	url='../lib/modules/list_modules.php?project_dir='+projectDir;
	
	//call the request
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);

}

function fireAlert(title,message){
	//set up button handler:
	var alertBody,alertTitle;
	var handlerYes = function() {
	
	//var data=getData(document.getElementById("inputform"));
	YAHOO.schema.container.alertDialog.hide();
	 return true;
	}; //default yes action
	var handlerNo = function (){
	YAHOO.schema.container.alertDialog.hide();
	//formBody.innerHTML='<form name="inputform" method="POST"  id="inputform"></form>';
	return false;
	}
	alertBody=document.getElementById('alertbody');
	alertHeader= document.getElementById('alertheader');
	
	//set up button, link to handler
	var myButtons = [ { text:"Yes",
	handler:handlerYes, isDefault:true },{text:"No",handler:handlerNo} ];
	YAHOO.schema.container.alertDialog.hide();
	//put buttons in configuration queue for processing
	YAHOO.schema.container.alertDialog.cfg.queueProperty("buttons", myButtons);
	alertBody.innerHTML=message;
	alertHeader.innerHTML=title;
	YAHOO.schema.container.alertDialog.render();
	YAHOO.schema.container.alertDialog.show();
	//alert('here');
//
}

function getData(formId) { 
var oForm = formId; 
if (oForm) { 
	var aElements = oForm.elements, nTotalElements = aElements.length, oData = {}, sName, oElement; 
	for (var i = 0; i < nTotalElements; i++) { 
		sName = aElements[i].name, oElement = aElements[sName]; 
		if (oElement) { 
			if (oElement.tagName) { 
				var sType = oElement.type, sTagName = oElement.tagName.toUpperCase(); 
				switch (sTagName) { 
					case "INPUT": 
						if (sType == "checkbox") { 
							oData[sName] = oElement.checked; 
						} else if (sType != "radio") { 
							oData[sName] = oElement.value; 
						} break; 
					case "TEXTAREA": oData[sName] = oElement.value; break; 
					case "SELECT": 
						var aOptions = oElement.options, nOptions = aOptions.length, aValues = [], oOption, sValue;
						for (var n = 0; n < nOptions; n++) { 
							oOption = aOptions[n]; 
							if (oOption.selected) { 
								sValue = oOption.value; 
								if (!sValue || sValue === "") { 
									sValue = oOption.text; 
								} 
								aValues[aValues.length] = sValue; 
							} 
						} 
						oData[sName] = aValues; break; 
					default:; 
				}
			} else { 
				var nElements = oElement.length, sType = oElement[0].type, sTagName = oElement[0].tagName.toUpperCase();
			
				switch (sType) { 
					case "radio": var oRadio; 
						for (var n = 0; n < nElements; n++) { 
							oRadio = oElement[n]; 
							if (oRadio.checked) { 
								oData[sName] = oRadio.value; break; 
							} 
						} break; 
					case "checkbox": 
						var aValues = [], oCheckbox; 
						for (var n = 0; n < nElements; n++) { 
							oCheckbox = oElement[n];
							if (oCheckbox.checked) { 
								aValues[aValues.length] = oCheckbox.value; 
							} 
						} 
						oData[sName] = aValues; break; 
					default:; 
				} 
			} 
		} 
	} 
} 
return oData; 
}


function getTypeModuleOptions(divname,typeModule,projectHome){
	var div;
	
	//function to handle success
	var handleSuccess = function(o){
		
		if(o.responseText !== undefined){	
			//replace the identified tag with the response text
			//this response contain either tables for the modules if they exist or message saying it doen't exit
			div.innerHTML =  o.responseText ;	
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	
	//set the div tag
	div = document.getElementById(divname);
	
	//set the value of the url
	url='../lib/modules/options_list.php?type_module='+typeModule+'&project_dir='+projectHome;
	
	
	//call the request
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

function getTypeTableOptions(divname,typeModule,typeTable,projectHome){

	var div;
	
	//function to handle success
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			//replace the identified tag with the response text
			//this response contain either tables for the modules if they exist or message saying it doen't exit
			div.innerHTML =  o.responseText ;	
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	
	//set the div tag
	div = document.getElementById(divname);
	
	//set the value of the url
	url='../lib/tables/options_list.php?type_module='+typeModule+'&type_table='+typeTable+'&project_home='+projectHome;
	//call the request
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

function editInheritance(tableName,tableId,moduleName,projectHome){
	var div;
	
	selectedModule = moduleName;
	
	//function to handle success
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			//replace the identified tag with the response text
			//this response contain either tables for the modules if they exist or message saying it doen't exit		
			div.innerHTML = '<div style="padding:20px;"><img src="../lib/images/back.png"'+
			'onclick="javascript:getModuleSchemaData(\''+moduleName+'\',\''+projectHome+'\');"'+
			' title="Go back to Entity view";"  /></div>'+
			'<div id="inheritance_tree" style="padding:60px 60px 30px 60px ;"></div>';
			drawInheritedTree(o.responseText,tableName,tableId,moduleName,projectHome);
			
			
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	
	//set the div tag
	div = document.getElementById('panel2_content');
	var title= document.getElementById('panel2_hd');
	
	//set the module name in header of right side panel
	title.innerHTML='<div class="tl"></div><span><b> '+moduleName+'>><i>'+tableName+'</i> (Interitance)</b></span><div class="tr"></div>';
	//set the value of the url
	url='../lib/inherited/list_inherited.php?table_name='+tableName +"&table_id="+tableId+"&module_name="+moduleName+"&project_home="+projectHome;
	
	panelStatus = EDIT_INHERITANCE;
	
	/**var iframe = document.getElementById("mainIframe");
	var user_token_input_ctrl = document.getElementById("user_token_input");
	var project_dir_input_ctrl = document.getElementById("project_dir_input");
	var user_token = user_token_input_ctrl.value;
	var project_dir = project_dir_input_ctrl.value;
	
	func_name = 'editInheritance';
	status = "&status="+ panelStatus;
	iframe.src= "frame_loader.php?func="+func_name+status+"&param1="+tableName"&param2="+tableId+"&param3="+moduleName+"&param4="+projectHome"&user_token="+user_token+"&project_dir="+project_dir;
	**/
	//call the request
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

function drawInheritedTree(hierarchy,tableName,tableId,moduleName,projectHome) {
	
	var tree = new YAHOO.widget.TreeView("inheritance_tree");
	var root = tree.getRoot();
	var moduleEntities=hierarchy.split('==');
	var moduleNames = new Array();
	var entityNames = new Array();
	var entityChecked = new Array();
	var moduleIndex =0;
	var entityIndex =0;
	
	for ( i=0; i < moduleEntities.length ;i ++)
	{
		var pair = moduleEntities[i].split('||');
		
		if( i >0 && (moduleNames[moduleIndex] != pair[0])){
			moduleIndex ++;
		}

		moduleNames[moduleIndex] = pair[0];
		if(!entityNames[moduleIndex]){
			entityNames[moduleIndex] = new Array();
		}
		if(!entityChecked[moduleIndex]){
			entityChecked[moduleIndex] = new Array();
		}
		entityNames[moduleIndex][entityIndex] = pair[1];
		entityChecked[moduleIndex][entityIndex++] = pair[2];
		//alert(pair[1]);
		//alert(pair[2]);
	}
	var moduleNode = new Array();
	for(i =0 ; i< moduleNames.length ; i++){			
		moduleNode[i] = new YAHOO.widget.TextNode(moduleNames[i],root,true);
		for (j =0 ; j< entityNames[i].length ; j++){
			entityNode = new YAHOO.widget.HTMLNode('<span><input type="checkbox"'+((entityChecked[i][j] =='yes')?'checked=true':'')+' onclick="javascript:inheritanceChanged(\''+tableName+'\',\''+tableId+'\',\''+moduleName+'\',\''+projectHome+'\',\''+entityNames[i][j]+'\',\''+moduleNames[i]+'\',this);"/>'+entityNames[i][j]+'</span>',moduleNode[i],true,true);
		}
	}
	tree.draw();
}

function inheritanceChanged(tableName,tableId,moduleName,projectHome,inheritedEntity,inheritedModule,target){
	var div;
	
	selectedModule = moduleName;
	
	//function to handle success
	var handleSuccess = function(o){
		if(o.responseText !== undefined){	
			editInheritance(tableName,tableId,moduleName,projectHome);
		}
	}
	
	//function to handle failure
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			//request failed
		}
	}

	//set call back handlers
	var callback =
	{
	  success:handleSuccess,
	  failure:handleFailure
	};
	if(target.checked){
		action = 'add';
	} else {
		action = 'remove';
	}
	//set the module name in header of right side panel
	//set the value of the url
	
	var url = '../lib/inherited/inherited_actions.php?action='+action+'&inherited_module='+inheritedModule+'&inherited_table='+inheritedEntity+'&table_id='+tableId+'&module_name='+moduleName+'&project_home='+projectHome;

	
	var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}



// callback for upload_module
//===============================================================================//
// Function to add module
// @args module, module id
function upModuleCallback(){

	moduleName = selectedModule;
	projectDir = selectedProject;
	target = selectedModuleDirectory;
	if(target == null)
	{
		alert("please select a Directory to Upload");
	}
	if(moduleName==null)
	{
		alert("please select a module to Upload");
	}
	else{
		url='../lib/modules/module_actions.php?action=up&module_name='+moduleName+'&'+
					'project_dir='+projectDir + '&target='+target;
		var suc= function(o)
		{
			// request success.
			var iframe = document.getElementById('sampleDirPanelFrame');
			var old_src = iframe.src;
			iframe.src = "";
			iframe.src = old_src;
			SEMF.currentPanel.hide();
		}
		var fail= function(o){
			// request failed
		}
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
	}
}

function upModule(project, projectDir)
{
	currentPanelId = 0;
	moduleName = selectedModule;
	if(moduleName==null)
	{
		alert("please select a module to Upload");
		return;
	}
	selectedProject = projectDir;
	SEMF.currentPanel = SEMF.sampleDirPanel;
	var titleElement = document.getElementById('sampleDirPanelTitle');
	titleElement.innerHTML = "Select a directory to upload the module..";
	SEMF.sampleDirPanel.hideEvent.subscribe(onCloseDirPanel);
	SEMF.sampleDirPanel.show();
}

function downModule(project, projectDir)
{
	currentPanelId = 1;
	selectedProject = projectDir;
	SEMF.currentPanel = SEMF.sampleDirPanel;
	var titleElement = document.getElementById('sampleDirPanelTitle');
	titleElement.innerHTML = "Select the module to download to the project..";
	SEMF.sampleDirPanel.hideEvent.subscribe(onCloseDirPanel);
	SEMF.sampleDirPanel.show();
}

SEMF.selectDirectory = function(dirName)
{
	selectedModuleDirectory = dirName;
}

// callback for download module
//===============================================================================//
// Function to add module
// @args module, module id
function downModuleCallback(){

	moduleName = selectedModule;
	projectDir = selectedProject;
	var source = selectedModuleDirectory;
	if(source == null)
	{
		alert("please select a module to download");
	}
	else{
		url='../lib/modules/module_actions.php?action=down&'+
					'project_dir='+projectDir + '&source='+source;
		var suc= function(o)
		{
			getModuleList(projectDir);
			SEMF.currentPanel.hide();
		}
		var fail= function(o){
			// request failed
		}
		var callbackfn={ success:suc,failure:fail };
		
		var request = YAHOO.util.Connect.asyncRequest('GET',url,callbackfn);
	}
}

function onCloseDirPanel()
{
	if(!SEMF.dirWinOked)
	{
		return;
	}
	SEMF.dirWinOked = false;
	if(currentPanelId == 0)
	{
		upModuleCallback();
	}
	else if(currentPanelId == 1)
	{
		downModuleCallback();
	}
}

function redirectPage(idName){
	var id= document.getElementById(idName);
	id.submit();
}